import json

import redis
import requests

proxies = {
    "http": "http://127.0.0.1:9000",  # HTTP 代理地址
    "https": "http://127.0.0.1:9000",  # HTTPS 代理地址
}

db1 = redis.Redis(host='localhost', port=6379, db=1)


def delete_list_element_by_index_optimized(key, index):
    """
    这个函数有问题，当index取1时，会把整个key删掉
    """
    list_len = db1.llen(key)  # 获取列表的长度
    if index < 0 or index >= list_len:  # 判断索引是否在有效范围内
        raise IndexError("Index out of range")

    # 删除指定索引位置的元素
    with db1.pipeline() as pipe:
        # 保留索引左侧元素
        if index > 0:
            pipe.ltrim(key, 0, index - 1)

        # 保留索引右侧元素
        if index < list_len - 1:
            pipe.ltrim(key, index + 1, -1)

        # 执行 Redis 管道操作
        pipe.execute()

def process_product_detail(product_id, smdzdm_category_value, smdzdm_brand_name, smdzdm_platform_name, platform_name, id,
                           smdzdm_san_ji_category, smdzdm_title, smdzdm_price, smdzdm_update_time, smdzdm_buy_platform,
                           smdzdm_buy_fang_an, smdzdm_order_num, smdzdm_pay_amount, smdzdm_start_shop_buy,
                           smdzdm_shop_buy_url, smdzdm_bao_liao_title, smdzdm_comment_img):
    """
    根据平台的商品详情URL格式不同处理商品信息
    """
    if platform_name == "京东":
        product_detail_url = f"http://cgi-bin.lottefuture.com/python/jd-goods-query.php?itemId={product_id}"
    elif platform_name == "淘宝":
        product_detail_url = f"http://cgi-bin.lottefuture.com/python/taobao-goods-query.php?itemId={product_id}"
    else:
        print(f"平台 {platform_name} 暂无处理逻辑")
        return

    # 获取商品详情
    product_detail_response = requests.get(product_detail_url, proxies=proxies, verify=False)
    product_detail_result = product_detail_response.json()

    if platform_name == "京东":
        product_list = product_detail_result.get("data", [])
    elif platform_name == "淘宝":
        product_list = product_detail_result.get("result_list", [])

    if not product_list:
        print(f"{platform_name}商品详情为空")
        return None

    for item in product_list:
        if platform_name == "京东":
            item_basic_info = item.get("categoryInfo")
            brand_name = item.get("brandName")
            category_name = "/".join([item_basic_info.get(f"cid{i}Name") for i in range(1, 4)])
        elif platform_name == "淘宝":
            item_basic_info = item.get('item_basic_info', {})
            brand_name = item_basic_info.get("brand_name")
            category_name = item_basic_info.get("category_name") + '/' + item_basic_info.get("level_one_category_name",
                                                                                             "")

        ti_huan_category = '/'.join(smdzdm_category_value.split('/', 3)[:3])
        ti_huan_brand = smdzdm_brand_name

        for key in item_basic_info.keys():
            if "Name" in key:
                item_basic_info[key] = ti_huan_category

        return {
            "id": id,
            "smdzdm_category_value": smdzdm_category_value,
            "smdzdm_product_id": product_id,
            "smdzdm_san_ji_category": smdzdm_san_ji_category,
            "smdzdm_brand_name": smdzdm_brand_name,
            "smdzdm_platform_name": smdzdm_platform_name,
            "smdzdm_title": smdzdm_title,
            "smdzdm_price": smdzdm_price,
            "smdzdm_update_time": smdzdm_update_time,
            "smdzdm_buy_platform": smdzdm_buy_platform,
            "smdzdm_buy_fang_an": smdzdm_buy_fang_an,
            "smdzdm_order_num": smdzdm_order_num,
            "smdzdm_pay_amount": smdzdm_pay_amount,
            "smdzdm_start_shop_buy": smdzdm_start_shop_buy,
            "smdzdm_shop_buy_url": smdzdm_shop_buy_url,
            "smdzdm_bao_liao_title": smdzdm_bao_liao_title,
            "smdzdm_comment_img": smdzdm_comment_img,
            "yuan_brand_name": brand_name,
            "yuan_category_name_he_bing": category_name,
            "ti_huan_category": ti_huan_category,
            "ti_huan_brand": ti_huan_brand
        }


def get_guang_fang_message():
    while True:
        # task = db1.lindex('smdzdm_product_message_queue', index)
        task = db1.lpop('smdzdm_product_message_queue')
        if task is None:
            print("redis数据库已没有任务---smdzdm_product_message_queue，爬取结束")
            break

        task = json.loads(task.decode('utf-8'))
        product_id = task.get('product_id')
        smdzdm_category_value = task.get('smdzdm_category_value')
        smdzdm_san_ji_category = task.get('smdzdm_san_ji_category')
        smdzdm_brand_name = task.get('smdzdm_brand_name')
        smdzdm_platform_name = task.get('platform_name')
        smdzdm_title = task.get('title')
        smdzdm_price = task.get('price')
        smdzdm_update_time = task.get("update_time")
        smdzdm_buy_platform = task.get("buy_platform")
        smdzdm_buy_fang_an = task.get("buy_fang_an")
        smdzdm_order_num = task.get("order_num")
        smdzdm_pay_amount = task.get("pay_amount")
        smdzdm_start_shop_buy = task.get("start_shop_buy")
        smdzdm_shop_buy_url = task.get("shop_buy_url")
        smdzdm_bao_liao_title = task.get("bao_liao_title")
        smdzdm_comment_img = task.get('comment_img')

        if smdzdm_platform_name in ["京东", "淘宝"]:
            product_detail = process_product_detail(
                product_id, smdzdm_category_value, smdzdm_brand_name, smdzdm_platform_name, smdzdm_platform_name,
                task.get("id"), smdzdm_san_ji_category, smdzdm_title, smdzdm_price, smdzdm_update_time,
                smdzdm_buy_platform, smdzdm_buy_fang_an, smdzdm_order_num, smdzdm_pay_amount, smdzdm_start_shop_buy,
                smdzdm_shop_buy_url, smdzdm_bao_liao_title, smdzdm_comment_img
            )

            if product_detail:
                db1.rpush("category_brand_dui_ying_message_queue", json.dumps(product_detail, ensure_ascii=False))
                print(f"成功获取{product_id}商品详情")
            else:
                #  暂存失败的任务
                task['fail_reason']="获取商品详情为空"
                db1.rpush("failed_task_queue", json.dumps(task, ensure_ascii=False))
                continue
        else:
            print(f"{smdzdm_platform_name}平台暂无处理流程")
            task['fail_reason'] = "无该平台对应的处理流程"
            #  暂存失败的任务
            db1.rpush("failed_task_queue", json.dumps(task, ensure_ascii=False))
            continue


if __name__ == '__main__':
    get_guang_fang_message()
